package com.lyk.swap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import net.sf.json.JSONObject;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.lyk.swap.orm.HibernateSessionFactory;
import com.lyk.swap.orm.Price;
import com.lyk.swap.orm.Product;
import com.lyk.swap.struts.action.BaseAction;

public class DataListener implements ServletContextListener {
	private Timer timer;
	private static final long PERIOD = 86400000;
	private long delay = 10000;

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		timer.cancel();
	}

	@SuppressWarnings("deprecation")
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		timer = new Timer(true);
		Date d = new Date();
		int h = d.getHours(), m = d.getMinutes();
		if (h < 17 || (h == 17 && m < 20)) {
			delay = (17 - h) * 3600000;
			if (m < 20) {
				delay += (20 - m) * 60000;
			}
		}
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				Calendar temp = Calendar.getInstance();
				temp.set(Calendar.HOUR_OF_DAY, 0);
				temp.set(Calendar.MINUTE, 0);
				temp.set(Calendar.SECOND, 0);
				temp.set(Calendar.MILLISECOND, 0);
				int dow = temp.get(Calendar.DAY_OF_WEEK);
				if (dow != Calendar.SATURDAY && dow != Calendar.SUNDAY) {
					Date date = temp.getTime();
					StringBuilder sb = new StringBuilder(
							RiskProfit.TICKERHEDDER);
					boolean nextyear = false;
					int month = date.getMonth();
					if (date.getDate() < WorkdayCalc.set3WorkdayBefore25(temp)) {
						if (month < 11) {
							sb.append(BaseAction.TICKER[month + 1]);
						} else {
							sb.append(BaseAction.TICKER[0]);
							nextyear = true;
						}
					} else {
						if (month < 10) {
							sb.append(BaseAction.TICKER[month + 2]);
						} else {
							if (month == 10) {
								sb.append(BaseAction.TICKER[0]);
							} else {
								sb.append(BaseAction.TICKER[1]);
							}
							nextyear = true;
						}
					}
					if (nextyear) {
						sb.append(date.getYear() - 110 + 1);
					} else {
						sb.append(date.getYear() - 110);
					}
					String surl = new String(RiskProfit.SURL);
					surl += new Date().getTime();
					surl += RiskProfit.MURL;
					surl += sb.toString();
					try {
						URL url = new URL(surl);
						HttpURLConnection httpConn = (HttpURLConnection) url
								.openConnection();
						BufferedReader br = new BufferedReader(
								new InputStreamReader(
										httpConn.getInputStream(), "utf-8"));
						String s = br.readLine();
						httpConn.disconnect();
						JSONObject jo = JSONObject.fromObject(s)
								.getJSONObject("marketDataInfoAsStringList")
								.getJSONObject("message");
						Session session = HibernateSessionFactory.getSession();
						Transaction transaction = session.beginTransaction();
						Product product = (Product) session.createCriteria(
								Product.class).uniqueResult();
						for (Price price : product.getPrices()) {
							if (date.equals(price.getTime())) {
								transaction.commit();
								return;
							}
						}
						product.getPrices().add(
								new Price(product, date, Double.parseDouble(jo
										.getString("settlePrice"))));
						session.saveOrUpdate(product);
						transaction.commit();
						System.out.println("Record success.");
					} catch (MalformedURLException e) {
						System.err
								.println("!!!ERROR: Error in recording price!!!");
					} catch (IOException e) {
						System.err
								.println("!!!ERROR: Error in recording price!!!");
					}
				}
			}

		}, delay, PERIOD);
	}

}
